#include "stdafx.h"
#include "spritespool.h"

namespace {
Sprite loadSprite(const QString &path, float depth = 0.0f)
{
    QImage image;
    {
        QImage temporary(path, 0);
        if (temporary.isNull())
        {
            qDebug() << "Can't load " << path;
            return Sprite();
        }
        if (temporary.hasAlphaChannel()) {
            image = temporary.convertToFormat(QImage::Format_ARGB32);
        }
        else
            image = temporary.convertToFormat(QImage::Format_RGB32);
        if (image.isNull())
        {
            qDebug() << "Convertion error on " << path;
            return Sprite();
        }
    }

    GLuint texture;
    glPixelStorei(GL_UNPACK_ALIGNMENT,4);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    // set anisotropic filtration level for this texture
    // (only if extension available)
//        if (GL_EXT_texture_filter_anisotropic)
//        {
//            GLint maxAnisotropy = 0;
//            glGetIntegerv(
//                GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,
//                &maxAnisotropy);
//            glTexParameteri(
//                GL_TEXTURE_2D,
//                GL_TEXTURE_MAX_ANISOTROPY_EXT,
//                maxAnisotropy);
//        }

    size_t internalFormat = (image.hasAlphaChannel()) ? 4 : 3;
    gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat,
                      image.width(), image.height(),
                      GL_BGRA, GL_UNSIGNED_BYTE,
                      image.bits());

    return Sprite(image.width(), image.height(), texture, depth);
}
}

SpritesPool::SpritesPool()
{
}

SpritesPool::~SpritesPool()
{
}

void SpritesPool::init()
{
    _mages[Color_Blue] = loadSprite("mage-blue.png", 0.1f);
    _spells[Spell_Fireball] = loadSprite("magic-arrow.spell.png", 0.15f);
    _spells[Spell_Frostball] = loadSprite("magic-arrow.spell.png", 0.15f);
    _spells[Spell_MagicArrow] = loadSprite("magic-arrow.spell.png", 0.15f);

    _manaPotions[Size_Small] = loadSprite("mana.potion.32.png");
    _manaPotions[Size_Medium] = loadSprite("mana.potion.48.png");
    _manaPotions[Size_Large] = loadSprite("mana.potion.64.png");
    _healthPotions[Size_Small] = loadSprite("health.potion.32.png");
    _healthPotions[Size_Medium] = loadSprite("health.potion.48.png");
    _healthPotions[Size_Large] = loadSprite("health.potion.64.png");
}

const Sprite &SpritesPool::spell(Spell spell) const
{
    return _spells[spell % SpellsNum];
}

const Sprite &SpritesPool::mage(Color color) const
{
    return _mages[color % ColorsNum];
}

const Sprite &SpritesPool::manaPotion(Size size) const
{
    return _manaPotions[size % SizesNum];
}

const Sprite &SpritesPool::healthPotion(Size size) const
{
    return _healthPotions[size % SizesNum];
}
